package com.example.basecommon.http.rxjava;

import android.text.TextUtils;

import com.example.basecommon.http.RequestErrorEvent;

import org.greenrobot.eventbus.EventBus;

import io.reactivex.Observer;
import io.reactivex.disposables.Disposable;

/**
 * 数据返回统一处理
 *
 * @param <T>
 */
public abstract class BaseObserver<T> implements Observer<BaseResponse<T>> {
    private static final String TAG = "BaseObserver";

    @Override
    public void onNext(BaseResponse<T> response) {
        //在这边对 基础数据 进行统一处理
        if (response.success == true || "200".equals(response.code)) {
            onSuccess(response);
        } else {
            if (!TextUtils.isEmpty(response.code)) {
                onFailure(response, response.msg);
            } else {
                onFailure(response, response.message.length() > 150 ? "应用程序异常!" : response.message);
            }
        }
    }

    @Override
    public void onError(Throwable e) {//服务器错误信息处理
        EventBus.getDefault().post(new RequestErrorEvent(e));
    }

    @Override
    public void onComplete() {

    }

    @Override
    public void onSubscribe(Disposable d) {

    }

    public abstract void onSuccess(BaseResponse<T> result);

    public abstract void onFailure(BaseResponse<T> result, String msg);

}
